﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Phoenix.Xna.Framework.Components;

namespace Phoenix.Xna.Framework.Graphics.Models
{
    public abstract class ModelBase : DrawableComponent, I3DComponent
    {
        protected int _updateOrder;
        protected int _drawOrder;
        protected Vector3 _eulerRotation;

        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed && disposing)
            {
                UnloadContent();

                foreach (IComponent c in SubComponents)
                {
                    c.Dispose();
                }

                IsDisposed = true;
            }
        }

        #region IComponent Members

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            Forward = Rotation.Forward;
            Up = Rotation.Up;
            Right = Rotation.Right;
            base.Update(gameTime);
        }

        #endregion

        #region I3DComponent Members

        [ContentSerializerIgnore]
        public Vector3 Forward { get; protected set; }
        [ContentSerializerIgnore]
        public Vector3 Up { get; protected set; }
        [ContentSerializerIgnore]
        public Vector3 Right { get; protected set; }
        [ContentSerializerIgnore]
        public Vector3 Position { get; set; }
        [ContentSerializerIgnore]
        public Vector2 Scale { get; set; }
        [ContentSerializerIgnore]
        public Vector3 EulerRotation
        {
            get { return _eulerRotation; }
            set
            {
                _eulerRotation = value;
                Rotation = Matrix.CreateFromYawPitchRoll(_eulerRotation.X, _eulerRotation.Y, _eulerRotation.Z);
            }
        }
        [ContentSerializerIgnore]
        public Matrix Rotation { get; protected set; }
        [ContentSerializerIgnore]
        public BoundingBox BoundingBox { get; protected set; }

        public void SetPosition(float? x, float? y, float? z)
        {
            float positionX = (x == null) ? Position.X : x.Value;
            float positionY = (y == null) ? Position.Y : y.Value;
            float positionZ = (x == null) ? Position.Z : z.Value;
            Position = new Vector3(positionX, positionY, positionZ);
        }

        public void SetEulerRotation(float? yaw, float? pitch, float? roll)
        {
            float x = (yaw == null) ? EulerRotation.X : yaw.Value;
            float y = (pitch == null) ? EulerRotation.Y : pitch.Value;
            float z = (roll == null) ? EulerRotation.Z : roll.Value;
            EulerRotation = new Vector3(x, y, z);
        }

        #endregion
    }
}
